package game.ghostleg;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class InSocket implements Runnable {
	
	private ServerSocket serverSocket;
	private GhostLegView world;
	public int ididid=-1;
	
	public InSocket() {
	}
	
	public InSocket(int portNum, GhostLegView world) {
		this.world = world;
		try {
			serverSocket = new ServerSocket(portNum);
			//serverSocket.setReuseAddress(true);
			
			System.err.printf("Create InSocket Successful, portNum : %d\n",portNum);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.err.printf("FAILED AT IN SOCKET(), portNum : %d\n", portNum );
			e.printStackTrace();
			portNum = portNum + 8;
			try {
				serverSocket = new ServerSocket(portNum);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} 
	}
	@Override
	public void run() {
		while(this.world.time>=-1000||this.world.time==-1) {
			
			try {
				Thread.sleep(200);
				System.err.printf("Inside Insocket %d run()\n",ididid);
				// accept() -> suspended until received a connection
				Socket socket = serverSocket.accept();
				ObjectInputStream in = new ObjectInputStream ( socket.getInputStream() );
				SocketData t=(SocketData)in.readObject();
				
				for(int i=t.val_int;i>=0;i--)
				{
					t=(SocketData)in.readObject();
					world.inData.add(t);
					this.world.inDirty++;
				}
				in.close();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		System.err.printf("InSocket %d bye\n",ididid);
		try {
			serverSocket.close();
			serverSocket = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

}
